﻿package com.example.jxel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;

import android.os.Handler;
import android.os.Message;

public class Jxel {
	
	/**
	 * 消息处理handler，方法执行在主线程
	 */
	private Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0x0:
				onFinish();
				break;
			case 0x1:
				onProgress();
				break;
			case 0x2:
				onStart();
				break;
			default:
				onError();
				break;
			}
		};
	};
	
	private Timer timer=new Timer();
	
	/**
	 * 向handler发送特定的消息
	 * @param code 要发送消息的消息码
	 */
	private void sendMessage(int code){
		Message msg=new Message();
		msg.what=code;
		handler.sendMessage(msg);
	}
	
	/**
	 * 下载目标url下的文件，存储至location
	 * 
	 * @param url 目标url
	 * @param location 存储位置
	 */
	public void down(final String url, final String location){
		Thread t=new Thread(new Runnable() {
			public void run() {
				// 发送开始消息
				sendMessage(0x2);
				try {
					URL target=new URL(url);
					try {
						File file=new File(location);
						file.createNewFile();
						RandomAccessFile raf=new RandomAccessFile(file, "rw");
						InputStream is=target.openStream();
						int len;
						byte[] buf=new byte[1024];
						while((len=is.read(buf))!=-1){
							raf.write(buf, 0, len);
						}
						sendMessage(0x0);
					} catch (FileNotFoundException e) {
						sendMessage(0x3);
						e.printStackTrace();
					} catch (IOException e) {
						sendMessage(0x3);
						e.printStackTrace();
					}
				} catch (MalformedURLException e) {
					sendMessage(0x3);
					e.printStackTrace();
				}
			}
		});
		t.start();
	}
	
	/**
	 * 执行于下载开始
	 */
	protected void onStart(){
		
	}
	
	/**
	 * 执行于下载过程中，每一定时间后执行一次
	 */
	protected void onProgress(){
		
	}
	
	/**
	 * 执行于下载结束
	 */
	protected void onFinish(){
		
	}
	
	/**
	 * 执行于出错
	 */
	protected void onError(){
		
	}
}
